from OpenGL.GL import *
from pyglet import app, window, clock, text
from pyglet.window import key

from common.map import Map
from game.core.gamemanager import GameManager
from game.ui.mainmenu import MainMenu
from game.ui.gameplay import GamePlay
from game.ui.loadingscreen import LoadingScreen 

class MainWindow(object):
	"""
	Class that runs the mainloop of the program.
	It represents the application's main window. 
	"""

	def __init__(self):
		GameManager.initialize(Map())
		GameManager.main_window = self
		
		self.win = window.Window(fullscreen=True, vsync=True)
		self.event_loop = app.EventLoop()
		
		self.win.push_handlers(self)
		
		clock.set_fps_limit(30)
		clock.schedule(self.tick)
		clock.schedule_interval(self.animate, 0.0625) # 16 fps
		
		self.loading_started = False
		self.loading = LoadingScreen()
		self.mainmenu = MainMenu()
		self.gameplay = GamePlay()
		
		self.init_gl()

	def init_gl(self):
		glEnable(GL_BLEND)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
		
		glEnable(GL_LIGHTING)
		glEnable(GL_COLOR_MATERIAL)
		glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, [1, 1, 1])
		glMaterial(GL_FRONT_AND_BACK, GL_SHININESS, 20)
		
	def tick(self, dt):
		if GameManager.state == GameManager.LOADING:
			if self.loading_started: return
			self.loading_started = True
			GameManager.load_models()
			self.change_mode(GameManager.MAIN_MENU)
		elif GameManager.state == GameManager.PLAYING:
			self.gameplay.tick(dt)
			
	def animate(self, dt):
		if GameManager.state == GameManager.PLAYING:
			self.gameplay.animate()
		
	def on_draw(self):
		pass
		
	def on_key_press(self, symbol, modifiers):
		pass
		
	def on_mouse_motion(self, x, y, dx, dy):
		pass
	
	def on_mouse_press(self, x, y, button, modifiers):
		pass

	def on_mouse_release(self, x, y, button, modifiers):
		pass

	def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
		pass
#	
	def start(self):
		self.win.push_handlers(self.loading)
		app.run()
		
	def quit(self):
		app.exit()
		
	def change_mode(self, newMode):
		self.win.pop_handlers()
		if newMode == GameManager.MAIN_MENU:
			self.win.push_handlers(self.mainmenu)
			GameManager.play_music('main_menu')
		elif newMode == GameManager.PLAYING:
			self.gameplay.initialize()
			self.win.push_handlers(self.gameplay)
			GameManager.play_music('game')
	
	